import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { LoginDto } from './dto/login-user.dto';
import { ResponseUtil } from '../common/utils/response.util';
import { ResponseResult } from '../common/interfaces/response.interface';
import { User } from './entities/user.entity';
import { BadRequestException } from '@nestjs/common';
import { DbService } from '../db/db.service';
import { Inject } from '@nestjs/common';
@Injectable()
export class UserService {

    @Inject(DbService)
    private readonly dbService: DbService;
   
   async login(loginDto: LoginDto): Promise<ResponseResult> {
    const users:User[] = await this.dbService.read();
    const foundUser = users.find(item => item.username === loginDto.username);
    if(!foundUser) {
        throw new BadRequestException('该用户不存在');
    }
    const data = {
      token: '1234567890',  
      user: foundUser
    }
    return ResponseUtil.success(data, 'Login successful');
   }

  async save(saveDto: LoginDto): Promise<ResponseResult> {
      const users:User[] = await this.dbService.read();
      console.log(users,"users");
      
      const foundUser = users.find(item => item.username === saveDto.username);
      if(foundUser) {
        throw new BadRequestException('该用户已经注册');
    }
      users.push(saveDto);
      await this.dbService.write(users);
      return ResponseUtil.success(users, 'Save successful');
   }
   async userInfo(): Promise<ResponseResult> {
    const data = {
      username: 'admin',
      userRole: 'admin',
      userid: '1234567890'
    }
    return ResponseUtil.success(data, 'User info');
   }

   async logout(): Promise<ResponseResult> {
    return ResponseUtil.success(null, 'Logout successful');
   }
}
